//
//  DownloadViewController.m
//  NetWork
//
//  Created by cocoazxj@163.com on 15/4/30.
//  Copyright (c) 2015年 handcool. All rights reserved.
//

#import "DownloadViewController.h"

@interface DownloadViewController ()<NSURLConnectionDataDelegate>
@property (nonatomic, strong) IBOutlet UIProgressView *pv_indicate;
@property (nonatomic, assign) long long total;
@property (nonatomic, assign) long long current;
@property (nonatomic, strong) NSFileHandle *fileHandle;
@end

@implementation DownloadViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)downloadButtonClicked:(id)sender
{
    NSURL *url = [NSURL URLWithString:@"http://192.168.0.77:8080/MJServer/resources/Hello.zip"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [NSURLConnection connectionWithRequest:request delegate:self];

}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    // 写入文件的路径
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"Hello.zip"];
    NSLog(@"-------------%@",path);
    
    // 文件管理类
    NSFileManager *manager = [NSFileManager defaultManager];
    
    // 创建文件
    [manager createFileAtPath:path contents:nil attributes:nil];
    self.fileHandle = [NSFileHandle fileHandleForWritingAtPath:path];
    self.total = response.expectedContentLength;
    NSLog(@"-------------%lld",response.expectedContentLength);
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    self.current += data.length;
    [self.pv_indicate setProgress:self.current/self.total animated:YES];
    [self.fileHandle seekToEndOfFile];
    [self.fileHandle writeData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"-------------connectionDidFinishLoading");
    [self.fileHandle closeFile];
    self.fileHandle = nil;
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    
}
@end
